<template>
  <div class="trading-view-container">
    <div id="chartContainer" ref="chartContainer"></div>
  </div>
</template>

<script>
  export default {
    name: 'TradingView',
    data() {
      return {
        chart: null
      }
    },
    mounted() {
      // 创建script标签
      const script = document.createElement('script')
      script.type = 'text/javascript'
      // 使用v3版本，这是一个稳定版本
      script.src = 'https://unpkg.com/lightweight-charts@3.8.0/dist/lightweight-charts.standalone.production.js'

      // 加载完成后初始化图表
      script.onload = () => {
        // 等待DOM更新
        this.$nextTick(() => {
          this.initChart()
        })
      }

      // 添加到文档
      document.head.appendChild(script)
    },
    methods: {
      initChart() {
        // 获取容器
        const container = this.$refs.chartContainer

        // 确保库加载成功
        if (!window.LightweightCharts) {
          console.error('图表库加载失败')
          return
        }

        // 基本配置
        const chartOptions = {
          width: container.clientWidth,
          height: 400, // 固定高度，避免使用clientHeight可能为0的问题
          layout: {
            backgroundColor: '#000000', // 黑色背景
            textColor: '#FFFFFF', // 白色文字
          },
          grid: {
            vertLines: {
              color: 'rgba(255, 255, 255, 0.1)',
            },
            horzLines: {
              color: 'rgba(255, 255, 255, 0.1)',
            },
          },
          crosshair: {
            mode: window.LightweightCharts.CrosshairMode.Normal,
            vertLine: {
              width: 1,
              color: 'rgba(255, 255, 255, 0.5)',
              style: 0,
            },
            horzLine: {
              width: 1,
              color: 'rgba(255, 255, 255, 0.5)',
              style: 0,
            }
          },
          localization: {
            timeFormatter: (time) => time,
            priceFormatter: (price) => price.toFixed(2)
          }
        }

        try {
          // 创建图表
          this.chart = window.LightweightCharts.createChart(container, chartOptions)

          // 添加K线图
          const mainSeries = this.chart.addCandlestickSeries({
            upColor: '#00ff00',
            downColor: '#ff0000',
            wickUpColor: '#00ff00',
            wickDownColor: '#ff0000',
            priceFormat: {
              type: 'price',
              precision: 2,
              minMove: 0.01,
            },
          })

          // 添加移动平均线
          const ma5Series = this.chart.addLineSeries({
            color: 'rgba(255, 144, 0, 1)',
            lineWidth: 1,
            priceFormat: {
              type: 'price',
              precision: 2,
            },
          })

          const ma10Series = this.chart.addLineSeries({
            color: 'rgba(0, 144, 255, 1)',
            lineWidth: 1,
            priceFormat: {
              type: 'price',
              precision: 2,
            },
          })

          // 添加交易量图
          const volumeSeries = this.chart.addHistogramSeries({
            color: '#00ff00',
            priceFormat: {
              type: 'volume',
            },
            priceScaleId: 'volume',
            scaleMargins: {
              top: 0.8,
              bottom: 0,
            },
          })

          // 示例数据
          const data = [{
              time: '2022-01-01',
              open: 25400,
              high: 25900,
              low: 25000,
              close: 25800
            },
            {
              time: '2022-01-02',
              open: 25800,
              high: 26100,
              low: 25600,
              close: 26000
            },
            {
              time: '2022-01-03',
              open: 26000,
              high: 26300,
              low: 25900,
              close: 26200
            },
            {
              time: '2022-01-04',
              open: 26200,
              high: 26400,
              low: 26000,
              close: 26300
            },
            {
              time: '2022-01-05',
              open: 26300,
              high: 26700,
              low: 26200,
              close: 26500
            }
          ]

          // 设置数据
          mainSeries.setData(data)

          // 自适应内容
          this.chart.timeScale().fitContent()

          // 添加移动平均线数据
          const ma5Data = [{
              time: '2022-01-01',
              value: 25600
            },
            {
              time: '2022-01-02',
              value: 25900
            },
            {
              time: '2022-01-03',
              value: 26100
            },
            {
              time: '2022-01-04',
              value: 26250
            },
            {
              time: '2022-01-05',
              value: 26400
            }
          ]

          const ma10Data = [{
              time: '2022-01-01',
              value: 25500
            },
            {
              time: '2022-01-02',
              value: 25800
            },
            {
              time: '2022-01-03',
              value: 26000
            },
            {
              time: '2022-01-04',
              value: 26150
            },
            {
              time: '2022-01-05',
              value: 26300
            }
          ]

          const volumeData = data.map(item => ({
            time: item.time,
            value: Math.random() * 1000 + 1000,
            color: item.close >= item.open ? '#00ff00' : '#ff0000'
          }))

          ma5Series.setData(ma5Data)
          ma10Series.setData(ma10Data)
          volumeSeries.setData(volumeData)

          // 添加鼠标移动事件监听
          this.chart.subscribeCrosshairMove((param) => {
            // 清除旧的tooltip
            const oldTooltip = document.querySelector('.tv-tooltip')
            if (oldTooltip) {
              oldTooltip.remove()
            }

            // 如果参数无效，直接返回
            if (!param || !param.time || !param.point) {
              return;
            }

            // 从当前时间获取数据
            const time = param.time;
            const timeStr =
              `${time.year}-${time.month.toString().padStart(2, '0')}-${time.day.toString().padStart(2, '0')}`;

            // 查找当前时间点对应的数据
            const currentData = data.find(item => item.time === timeStr);
            const currentMA5 = ma5Data.find(item => item.time === timeStr);
            const currentMA10 = ma10Data.find(item => item.time === timeStr);
            const currentVolume = volumeData.find(item => item.time === timeStr);

            if (currentData) {
              // 创建tooltip
              const tooltip = document.createElement('div');
              tooltip.className = 'tv-tooltip';
              tooltip.style.position = 'absolute';
              tooltip.style.left = param.point.x + 'px';
              tooltip.style.top = param.point.y + 'px';
              tooltip.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
              tooltip.style.color = 'white';
              tooltip.style.padding = '8px';
              tooltip.style.borderRadius = '4px';
              tooltip.style.fontSize = '12px';
              tooltip.style.zIndex = '1000';

              // 构建tooltip内容
              let content = `时间: ${timeStr}<br>`;
              content += `开盘: ${currentData.open.toFixed(2)}<br>`;
              content += `最高: ${currentData.high.toFixed(2)}<br>`;
              content += `最低: ${currentData.low.toFixed(2)}<br>`;
              content += `收盘: ${currentData.close.toFixed(2)}<br>`;

              // 添加MA数据
              if (currentMA5) {
                content += `MA5: ${currentMA5.value.toFixed(2)}<br>`;
              } else {
                content += `MA5: -<br>`;
              }

              if (currentMA10) {
                content += `MA10: ${currentMA10.value.toFixed(2)}<br>`;
              } else {
                content += `MA10: -<br>`;
              }

              // 添加成交量数据
              if (currentVolume) {
                content += `成交量: ${Math.round(currentVolume.value).toLocaleString()}`;
              } else {
                content += `成交量: -`;
              }

              tooltip.innerHTML = content;
              document.body.appendChild(tooltip);
            }
          });

          // 点击时移除tooltip
          this.chart.subscribeClick(() => {
            const tooltip = document.querySelector('.tv-tooltip')
            if (tooltip) {
              tooltip.remove()
            }
          });

          // 鼠标离开图表区域时移除tooltip
          container.addEventListener('mouseleave', () => {
            const tooltip = document.querySelector('.tv-tooltip')
            if (tooltip) {
              tooltip.remove()
            }
          });

          // 窗口大小变化时调整图表大小
          window.addEventListener('resize', this.handleResize)
        } catch (e) {
          console.error('创建图表失败:', e)
        }
      },
      handleResize() {
        if (this.chart) {
          const container = this.$refs.chartContainer
          this.chart.applyOptions({
            width: container.clientWidth
          })
        }
      }
    },
    beforeDestroy() {
      // 清理事件监听
      window.removeEventListener('resize', this.handleResize)

      // 清理图表
      if (this.chart) {
        this.chart = null
      }

      // 清理tooltip
      const tooltip = document.querySelector('.tv-tooltip')
      if (tooltip) {
        tooltip.remove()
      }
    }
  }
</script>

<style scoped>
  .trading-view-container {
    width: 100%;
    height: 400px;
    position: relative;
  }

  #chartContainer {
    width: 100%;
    height: 100%;
  }

  .tv-tooltip {
    pointer-events: none;
    white-space: nowrap;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  }
</style>
